package com.yuanjun.product.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanjun.product.entity.JczSysAdmin;
import com.yuanjun.product.entity.JczUser;
import com.yuanjun.product.service.HomeService;
import com.yuanjun.product.service.UserService;
import com.yuanjun.product.utils.MD5Util;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.req.LoginReq;
import com.yuanjun.product.vo.req.RegisterReq;
import com.yuanjun.product.vo.req.ReqIndexVo;
import com.yuanjun.product.vo.req.ReqLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yuanjun.product.vo.common.Const;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/home")
public class HomeController {
    @Autowired
    private HomeService homeService;
    @Resource
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param registerReq
     * @return
     */
    @RequestMapping("/register")
    public BaseResult register(@RequestBody RegisterReq registerReq){
        //验证手机号是否已经注册
        boolean flag = userService.checkPhone(registerReq.getContactPhone());
        if(!flag){
            return BaseResult.createFail(Const.HttpRespCode.DATA_REPEAT,"该手机号已注册，请前往登录");
        }
        //判断密码是否包含特殊字符
        if(userService.isSpecialChar(registerReq.getPassword())){
            return BaseResult.createFail(Const.HttpRespCode.INCOMPATIBLE_CONDITION,"密码中包含特殊字符，请修改后重新提交");
        }
        //判断手机验证码
        if (!stringRedisTemplate.hasKey(registerReq.getCaptchaToken())) {
            return BaseResult.createFail(400, "验证码超时请重新获取");
        }
        if (!stringRedisTemplate.opsForValue().get(registerReq.getCaptchaToken()).equals(registerReq.getRandomCode())) {
            return BaseResult.createFail(400, "验证码错误");
        }
        return BaseResult.createOk(userService.register(registerReq));
    }

    /**
     * 登录
     * @param loginReq
     * @return
     */
    @RequestMapping("/login")
    public BaseResult login(@RequestBody LoginReq loginReq){
        //验证码登录
        if(loginReq.getFlag()==0){
            if (StringUtils.isBlank(loginReq.getUserPhone())||StringUtils.isBlank(loginReq.getRandomCode())) {
                return BaseResult.createFail(Const.HttpRespCode.DATA_LACK, "手机号或验证码为空");
            }
            if (!stringRedisTemplate.hasKey(loginReq.getCaptchaToken())) {
                return BaseResult.createFail(400, "验证码超时请重新获取");
            }
            if (!stringRedisTemplate.opsForValue().get(loginReq.getCaptchaToken()).equals(loginReq.getRandomCode())) {
                return BaseResult.createFail(400, "验证码错误");
            }
            //判断数据库是否存在改用户
            JczUser user=userService.login(loginReq.getUserPhone());
            if (user==null){
                return BaseResult.createFail(Const.HttpRespCode.INCOMPATIBLE_CONDITION, "无此账户");
            }
            String token = Const.FRONT_PREFIX + "-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis();
            log.info("生成的token:{}", token);
            //存放user表对象
            stringRedisTemplate.opsForValue().set(token, JSONObject.toJSONString(user), 3600, TimeUnit.SECONDS);
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            map.put("userName",user.getUserName());
            return BaseResult.createOk(map);
        }
        //手机号 密码登录
        else{
            if (StringUtils.isBlank(loginReq.getUserPhone())||StringUtils.isBlank(loginReq.getPassword())) {
                return BaseResult.createFail(Const.HttpRespCode.DATA_LACK, "账号或密码不能为空");
            }
            //密码加密
            String password = MD5Util.encrypt(loginReq.getPassword());
            loginReq.setPassword(password);
            //数据库中是否存在该手机号
            JczSysAdmin user = userService.phoneLogin(loginReq.getUserPhone());
            if (user==null){
                return BaseResult.createFail(Const.HttpRespCode.DATA_LACK, "手机号或密码错误，请重新输入");
            }
            if (!loginReq.getPassword().equals(user.getPassword())){
                return BaseResult.createFail(Const.HttpRespCode.INCOMPATIBLE_CONDITION, "您输入的密码不正确，请重新输入");
            }
            JczUser jczUser=userService.findUserByPhone(user.getPhone());
            String token = Const.FRONT_PREFIX + "-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis();
            log.info("生成的token:{}", token);
            stringRedisTemplate.opsForValue().set(token, JSONObject.toJSONString(jczUser), 3600, TimeUnit.SECONDS);
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            map.put("userName",jczUser.getUserName());
            return BaseResult.createOk(map);
        }
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping("/modifyPassword")
    public BaseResult modifyPassword(@RequestBody LoginReq loginReq){
        //判断手机验证码
        if (!stringRedisTemplate.hasKey(loginReq.getCaptchaToken())) {
            return BaseResult.createFail(400, "验证码超时请重新获取");
        }
        if (!stringRedisTemplate.opsForValue().get(loginReq.getCaptchaToken()).equals(loginReq.getRandomCode())) {
            return BaseResult.createFail(400, "验证码错误");
        }
        //判断密码是否包含特殊字符
        if(userService.isSpecialChar(loginReq.getPassword())){
            return BaseResult.createFail(Const.HttpRespCode.INCOMPATIBLE_CONDITION,"密码中包含特殊字符，请修改后重新提交");
        }
        //密码加密
        String password = MD5Util.encrypt(loginReq.getPassword());
        loginReq.setPassword(password);
        return userService.modifyPassword(loginReq);
    }

    /**
     * 首页信息
     * @param token
     * @return
     */
    @RequestMapping("/index")
    public BaseResult index(@RequestHeader(Const.PROFRONTTOKEN) String token) {
        String userJson = stringRedisTemplate.opsForValue().get(token);
        JczUser user = new JczUser();
        if(!StringUtils.isBlank(userJson)){
            user = JSON.parseObject(userJson, JczUser.class);
        }else{
            user = null;
        }
        return homeService.index(user);
    }
}
